package com.ts.oa.service.impl;

import com.ts.common.service.DictService;
import com.ts.common.utils.DataPerUitl;
import com.ts.common.utils.DateUtils;
import com.ts.common.utils.PageInfos;
import com.ts.common.utils.PageUtils;
import com.ts.oa.dao.ExNotifyDao;
import com.ts.oa.dao.NotifyDao;
import com.ts.oa.dao.NotifyRecordDao;
import com.ts.oa.domain.NotifyDO;
import com.ts.oa.domain.NotifyDTO;
import com.ts.oa.domain.NotifyRecordDO;
import com.ts.oa.service.NotifyService;
import com.ts.system.dao.UserDao;
import com.ts.system.domain.UserDO;
import com.ts.system.service.SessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class NotifyServiceImpl implements NotifyService {
    @Autowired
    private NotifyDao notifyDao;
    @Autowired
    private ExNotifyDao exNotifyDao;
    @Autowired
    private NotifyRecordDao recordDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private DictService dictService;
    @Autowired
    private SessionService sessionService;
    @Autowired
    private SimpMessagingTemplate template;

    @Override
    public NotifyDO get(Long id) {
        NotifyDO rDO = notifyDao.get(id);
        return rDO;
    }

    @Override
    public List<Map<String, Object>> list(Map<String, Object> map) {
        map.putAll(DataPerUitl.userPer("create_By"));
        List<Map<String, Object>> notifys = exNotifyDao.list(map);
        return notifys;
    }

    @Override
    public int count(Map<String, Object> map) {
        return notifyDao.count(map);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(NotifyDO notify) {
        notify.setUpdateDate(new Date());
        int r = notifyDao.save(notify);
        // 保存到接受者列表中
        Long[] userIds = notify.getUserIds();
        if (userIds.length > 0) {
            Long notifyId = notify.getId();
            List<NotifyRecordDO> records = new ArrayList<>();
            for (Long userId : userIds) {
                NotifyRecordDO record = new NotifyRecordDO();
                record.setNotifyId(notifyId);
                record.setUserId(userId);
                record.setIsRead(0);
                records.add(record);
            }
            recordDao.batchSave(records);
        }
        //给在线用户发送通知
        //        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>());
        //        executor.execute(new Runnable() {
        //            @Override
        //            public void run() {
        //                for (UserDO userDO : sessionService.listOnlineUser()) {
        //                    for (Long userId : userIds) {
        //                        if (userId.equals(userDO.getUserId())) {
        //                            template.convertAndSendToUser(userDO.toString(), "/queue/notifications", "新消息：" + notify.getTitle());
        //                        }
        //                    }
        //                }
        //            }
        //        });
        //        executor.shutdown();
        return r;
    }

    @Override
    public int update(NotifyDO notify) {
        Long[] userIds = notify.getUserIds();
        if (userIds.length > 0) {
            Long notifyId = notify.getId();
            List<NotifyRecordDO> records = new ArrayList<>();
            for (Long userId : userIds) {
                NotifyRecordDO record = new NotifyRecordDO();
                record.setNotifyId(notifyId);
                record.setUserId(userId);
                record.setIsRead(0);
                records.add(record);
                exNotifyDao.updateNotify(records);
            }
        }
        return notifyDao.update(notify);
    }

    @Transactional
    @Override
    public int remove(Long id) {
        recordDao.removeByNotifbyId(id);
        return notifyDao.remove(id);
    }

    @Transactional
    @Override
    public int batchRemove(Long[] ids) {
        recordDao.batchRemoveByNotifbyId(ids);
        return notifyDao.batchRemove(ids);
    }


    @Override
    public PageUtils selfList(Map<String, Object> map) {
        //查询列表数据
        PageUtils pageUtils = new PageInfos(map) {
            @Override
            public List inject(Map params) {
                List<NotifyDTO> inputsList = notifyDao.listDTO(params);
                return inputsList;
            }
        }.query();
        for (Object obj : pageUtils.getRows()) {
            NotifyDTO notifyDTO = (NotifyDTO) obj;
            notifyDTO.setBefore(DateUtils.getTimeBefore(notifyDTO.getUpdateDate()));
            notifyDTO.setSender(userDao.get(notifyDTO.getCreateBy()).getName());
        }
        return pageUtils;
    }

}
